"""
文件上传模型模块
"""

import os
import json
import base64
import hashlib

from jlpay.model.base import OrgBaseReq, BaseResponse


class FileUploadRequest(OrgBaseReq):
    """文件上传请求类"""
    
    API_PREFIX = "/open/file"
    API_URI = "/upload"
    
    def __init__(self):
        """初始化文件上传请求对象"""
        super().__init__()
        self.file_type = None
        self.file_path = None
        self._file = None
    
    def set_file_type(self, file_type):
        """
        设置文件类型
        
        Args:
            file_type: 文件类型
            
        Returns:
            FileUploadRequest实例
        """
        self.file_type = file_type
        return self
    
    def set_file_path(self, file_path):
        """
        设置文件路径
        
        Args:
            file_path: 文件路径
            
        Returns:
            FileUploadRequest实例
        """
        self.file_path = file_path
        # 打开文件
        self._file = ('file', open(file_path, 'rb'), os.path.basename(file_path))
        return self
    
    def to_dict(self):
        """
        将请求对象转换为字典
        
        Returns:
            字典对象
        """
        return {
            'org_no': self.org_no,
            'merch_no': self.merch_no,
            'file_type': self.file_type
        }
    
    def get_file(self):
        """
        获取文件对象
        
        Returns:
            文件对象
        """
        return self._file


class FileUploadResponse(BaseResponse):
    """文件上传响应类"""
    
    def __init__(self, response_dict=None):
        """
        初始化文件上传响应对象
        
        Args:
            response_dict: 响应字典
        """
        super().__init__(response_dict)
        self.file_url = None
        self.media_id = None
        
        if response_dict:
            self.file_url = response_dict.get('file_url')
            self.media_id = response_dict.get('media_id')
    
    def get_file_url(self):
        """
        获取文件URL
        
        Returns:
            文件URL
        """
        return self.file_url
    
    def get_media_id(self):
        """
        获取媒体文件ID
        
        Returns:
            媒体文件ID
        """
        return self.media_id


# =================== 商管文件上传请求类 =====================
class MerchantFileUploadRequest(OrgBaseReq):
    """商管文件上传请求基类"""
    
    API_PREFIX = "/base/file"
    
    def __init__(self):
        """初始化文件上传请求对象"""
        super().__init__()
        self.meta = None  # 媒体文件元信息
        self.file = None  # 文件二进制内容
    
    def set_meta(self, filename, file_content):
        """
        设置媒体文件元信息
        
        Args:
            filename: 文件名称
            file_content: 文件内容（二进制）
            
        Returns:
            MerchantFileUploadRequest实例
        """
        # 计算文件SM3摘要
        digest = hashlib.new('sm3')
        digest.update(file_content)
        abstract = base64.b64encode(digest.digest()).decode('utf-8')
        
        meta_info = {
            "filename": filename,
            "alg": "SM3",
            "abstract": abstract
        }
        
        self.meta = json.dumps(meta_info, ensure_ascii=False)
        return self
    
    def set_file(self, file_content):
        """
        设置文件内容
        
        Args:
            file_content: 文件二进制内容
            
        Returns:
            MerchantFileUploadRequest实例
        """
        self.file = file_content
        return self
    
    def set_file_from_path(self, file_path):
        """
        从文件路径读取并设置文件内容
        
        Args:
            file_path: 文件路径
            
        Returns:
            MerchantFileUploadRequest实例
        """
        with open(file_path, 'rb') as f:
            file_content = f.read()
            
        filename = os.path.basename(file_path)
        self.set_meta(filename, file_content)
        self.set_file(file_content)
        return self


class ImageUploadRequest(MerchantFileUploadRequest):
    """图片上传请求类"""
    
    def get_api_uri(self):
        """获取API URI"""
        return "/base/file/upload/image"


class VideoUploadRequest(MerchantFileUploadRequest):
    """视频上传请求类"""
    
    def get_api_uri(self):
        """获取API URI"""
        return "/base/file/upload/video"


class PdfUploadRequest(MerchantFileUploadRequest):
    """PDF上传请求类"""
    
    def get_api_uri(self):
        """获取API URI"""
        return "/base/file/upload/pdf" 